#include "usermanagement.h"
#include <QScrollBar>
#include <QScroller>
#include <QStandardItem>
#include <mainwindow.h>
#include <transparentbutton.h>
#include "MessageBox.h"
#include "userdialog.h"
#include "models/databasemanager.h"
#include "userdialog.h"
UserManagement::UserManagement(QWidget *parent)
    : QWidget(parent)
{
    initUI();
    setupListView();
    
    connect(addButton, &QPushButton::clicked, this, &UserManagement::onAddButtonClicked);
}

void UserManagement::initUI()
{
    // 设置背景颜色和全局字体
    setStyleSheet(
        "QWidget {"
        "    background-color: #1F1F1F;"
        "    font-family: '微软雅黑';"
        "}"
        );
    
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);

    // 创建头部区域
    QWidget *headerWidget = new QWidget;
    headerWidget->setFixedHeight(50*g_xScale);
    QHBoxLayout *titleLayout = new QHBoxLayout(headerWidget);
    titleLayout->setContentsMargins(28*g_xScale, 0, 28*g_xScale, 0);

    // 创建标题标签
    QLabel *titleLabel = new QLabel("用户管理");
    titleLabel->setStyleSheet(QString(
        "color: white;"
         "font:%1px \'微软雅黑\';").arg(int(20*g_xScale)));


   QString btnStyle=QString("QPushButton{\
        background:transparent; \
        color:#007BFF;\
        font:%1px \"微软雅黑\"; \
        border-color: #098CFF;\
        border-width:1px;}\
        QPushButton:pressed{ \
        color:#0056b3;}").arg(int(20*g_xScale));
    // 创建新增按钮
    addButton = new TouchButton("新建");
    addButton->setStyleSheet(btnStyle);

    titleLayout->addWidget(titleLabel);
    titleLayout->addStretch();
    titleLayout->addWidget(addButton);

    // 在添加 ListView 之前，创建表头
    QWidget *tableHeader = new QWidget;
    tableHeader->setFixedHeight(50*g_xScale);
    tableHeader->setStyleSheet("background-color: #2E2F31;");
    
    QHBoxLayout *headerLayout = new QHBoxLayout(tableHeader);
    headerLayout->setContentsMargins(28*g_xScale, 0, 28*g_xScale, 0);
    headerLayout->setSpacing(20*g_xScale);  // 添加列间距
    
    // 创建表头标签
    QString labelStyle=QString("color: white;"
                                 "font:%1px \'微软雅黑\';").arg(int(20*g_xScale));

    QLabel *numHeader = new QLabel("序号");
    numHeader->setStyleSheet(labelStyle);
    numHeader->setFixedWidth(80*g_xScale);
    numHeader->setAlignment(Qt::AlignCenter);
    
    QLabel *nameHeader = new QLabel("用户名");
    nameHeader->setStyleSheet(labelStyle);
    nameHeader->setMinimumWidth(200*g_xScale);  // 改为最小宽度
    nameHeader->setAlignment(Qt::AlignCenter);
    
    QLabel *permHeader = new QLabel("用户权限");
    permHeader->setStyleSheet(labelStyle);
    permHeader->setMinimumWidth(200*g_xScale);  // 改为最小宽度
    permHeader->setAlignment(Qt::AlignCenter);
    
    QLabel *operHeader = new QLabel("操作");
    operHeader->setStyleSheet(labelStyle);
    operHeader->setMinimumWidth(200*g_xScale);  // 设置最小宽度
    operHeader->setAlignment(Qt::AlignCenter);
    
    headerLayout->addWidget(numHeader);
    headerLayout->addWidget(nameHeader, 1);        // 添加拉伸因子
    headerLayout->addWidget(permHeader, 1);        // 添加拉伸因子
    headerLayout->addWidget(operHeader, 1);        // 添加拉伸因子

    // 创建ListView
    listView = new QListView;
    listView->setVerticalScrollMode(QListView::ScrollPerPixel);
    QScroller::grabGesture(listView, QScroller::LeftMouseButtonGesture);
    listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    listView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    model = new QStandardItemModel(this);
    listView->setModel(model);
    // 设置ListView样式
    listView->setStyleSheet(QString(
        "QListView {"
        "    background-color: #1F1F1F;"
        "    border: none;"
        "    font:%1px \"微软雅黑\";"
        "}"
        "QListView::item {"
        "    background-color: #252627;"
        "    border: none;"
        "    color: white;"
        "    height:%2px"
        "}"
        "QListView::item:alternate {"
        "    background-color: #2E2F31;"
        "}"
        "QListView::item:selected {"
        "    background-color: #1E90FF;"
        "}"
        "QListView::item:hover {"
        "    background-color: #3E4145;"
        "}"
        "QScrollBar:vertical {"
        "    background-color: #1F1F1F;"
        "}"
        "QScrollBar::handle:vertical {"
        "    background-color: #4A4A4A;}").arg(int(18*g_xScale)).arg(int(50*g_xScale)));

    listView->setAlternatingRowColors(true);
    listView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    listView->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    listView->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 设置选择模式
    listView->setSelectionMode(QAbstractItemView::SingleSelection);
    listView->setSelectionBehavior(QAbstractItemView::SelectRows);

    mainLayout->addWidget(headerWidget);  // 添加顶部的标题栏
    mainLayout->addWidget(tableHeader);   // 添加表头
    mainLayout->addWidget(listView);      // 添加列表视图
}

void UserManagement::setupListView()
{
    //初始化数据库的数据
    QList<UserInfo> listUserInfo=DatabaseManager::getInstance()->getUsers();
    for (int i = 0; i < listUserInfo.count(); ++i) {
        addUserToModel(listUserInfo[i].nPermission,listUserInfo[i].userName,model->rowCount());
    }
}

void UserManagement::addUserToModel(int permission, QString strUserName, int row)
{
    //插入到数据库 并更新列表
    QWidget *itemWidget = new QWidget(listView);
    // 设置交替背景色
    itemWidget->setStyleSheet(QString("background-color: %1;")
                                  .arg(row % 2 == 0 ? "#252627" : "#2E2F31"));

    QHBoxLayout *itemLayout = new QHBoxLayout(itemWidget);
    itemLayout->setContentsMargins(28*g_xScale, 0, 28*g_xScale, 0);
    itemLayout->setSpacing(20*g_xScale);  // 添加列间距

    // 更新标签样式
    QString labelStyle =QString(
        "color: white;"
        "background: transparent;"
          "font:%1px \'微软雅黑\';").arg(int(18*g_xScale));

    // 序号
    QLabel *numLabel = new QLabel(QString::number(row+ 1));
    numLabel->setStyleSheet(labelStyle);
    numLabel->setFixedWidth(80*g_xScale);
    numLabel->setAlignment(Qt::AlignCenter);

    // 用户名
    QLabel *nameLabel = new QLabel(strUserName);
    nameLabel->setStyleSheet(labelStyle);
    nameLabel->setMinimumWidth(200*g_xScale);  // 改为最小宽度
    nameLabel->setAlignment(Qt::AlignCenter);

    // 用户权限
    QLabel *permLabel = new QLabel(permission==0?"开发者":"普通用户");
    permLabel->setStyleSheet(labelStyle);
    permLabel->setMinimumWidth(200*g_xScale);  // 改为最小宽度
    permLabel->setAlignment(Qt::AlignCenter);

    // 操作按钮
    QWidget *btnWidget = new QWidget;
    btnWidget->setStyleSheet("background: transparent;");
    QHBoxLayout *btnLayout = new QHBoxLayout(btnWidget);
    btnLayout->setContentsMargins(20*g_xScale, 0, 0, 0);  // 移除内边距
    btnLayout->setSpacing(8*g_xScale);  // 设置按钮之间的间距
    btnWidget->setMinimumWidth(100*g_xScale);

    TransparentButton *editBtn = new TransparentButton("编辑");
    editBtn->setFixedSize(60*g_xScale,45*g_xScale);
    connect(editBtn, &TransparentButton::clicked, this, &UserManagement::onEditButtonClicked);
    TransparentButton *deleteBtn = new TransparentButton("删除");
    deleteBtn->setFixedSize(60*g_xScale,45*g_xScale);
    connect(deleteBtn, &TransparentButton::clicked, this, &UserManagement::onDeleteButtonClicked);

        QString btnStyle=QString("QPushButton{\
                            background:transparent; \
                            color:#007BFF;\
                            font:%1px \"微软雅黑\"; \
                            border-color: #098CFF;\
                            border-width:1px;}\
                            QPushButton:pressed{ \
                            color:#0056b3; \
                            } \
                            QPushButton:disabled { \
                            color: gray; \
                            }").arg(int(18*g_xScale));
    editBtn->setStyleSheet(btnStyle);
    deleteBtn->setStyleSheet(btnStyle);

    // 使用QHBoxLayout来居中显示按钮
    QHBoxLayout *centerLayout = new QHBoxLayout;
    centerLayout->setSpacing(29*g_xScale);
    centerLayout->addStretch();  // 左侧弹簧
    centerLayout->addWidget(editBtn);
    centerLayout->addWidget(deleteBtn);
    centerLayout->addStretch();  // 右侧弹簧
    btnLayout->addLayout(centerLayout);  // 将居中布局添加到按钮容器中

    itemLayout->addWidget(numLabel);
    itemLayout->addWidget(nameLabel, 1);       // 添加拉伸因子
    itemLayout->addWidget(permLabel, 1);       // 添加拉伸因子
    itemLayout->addWidget(btnWidget, 1);       // 添加拉伸因子

    QStandardItem *item = new QStandardItem;
    model->insertRow(row, item);
    listView->setIndexWidget(item->index(), itemWidget);
}

void UserManagement::updateUserInModel(int permission, QString strUserName, int row)
{
    if (row >= 0 && row < model->rowCount()) {
        model->removeRow(row);
        addUserToModel(permission,strUserName, row);
    }
}

void UserManagement::removeUserFromModel(int row)
{
    if (row >= 0 && row < model->rowCount()) {
        model->removeRow(row);
        // 更新序号
        for (int i = row; i < model->rowCount(); i++) {
            QModelIndex index = model->index(i, 0);
            QWidget *widget = listView->indexWidget(index);
            if (widget) {
                QLabel *numLabel = widget->findChild<QLabel*>();
                if (numLabel) {
                    numLabel->setText(QString::number(i + 1));
                }
                // 设置交替背景色
                widget->setStyleSheet(QString("background-color: %1;")
                                          .arg(i % 2 == 0 ? "#252627" : "#2E2F31"));
            }
        }
    }
}

int UserManagement::getCurrentRow() const
{
    QModelIndex currentIndex = listView->currentIndex();
    return currentIndex.isValid() ? currentIndex.row() : -1;
}

void UserManagement::onAddButtonClicked()
{
    QString strErr;
    UserDialog dialog(UserDialog::Add, this);
    if (dialog.exec() == QDialog::Accepted) {
        // 获取用户输入的数据
        int permission = dialog.getUserRole();
        QString name = dialog.getUserName();
        addUserToModel(permission,name,model->rowCount());
    }
}

void UserManagement::onEditButtonClicked()
{
    int currentRow = getCurrentRow();
    if (currentRow < 0) return;
    UserDialog dialog(UserDialog::Edit, MainWindow::getInstance());
    // 获取当前用户数据并设置到对话框
    QModelIndex index = model->index(currentRow, 0);
    QWidget *widget = listView->indexWidget(index);
    if (widget) {
        QList<QLabel*> labels = widget->findChildren<QLabel*>();
        if (labels.size() >= 3) {
            QString name = labels[1]->text();
            QString permission = labels[2]->text();
            dialog.setUserData(name,permission == "开发者" ? UserDialog::Developer : UserDialog::Normal,"********");
        }
    }
    if (dialog.exec() == QDialog::Accepted) {
        // 获取用户修改后的数据
        QString name = dialog.getUserName();
        int permission = dialog.getUserRole();
        updateUserInModel(permission,name,currentRow);
    }
    listView->update();
}

void UserManagement::onDeleteButtonClicked()
{
    int currentRow = getCurrentRow();
    if (currentRow >= 0) {
        QString strUserName;
        QModelIndex index = model->index(currentRow, 0);
        QWidget *widget = listView->indexWidget(index);
        if (widget) {
            QList<QLabel*> labels = widget->findChildren<QLabel*>();
            if (labels.size() >= 3) {
                strUserName = labels[1]->text();
            }
        }
        //确认对话框
        if(question(MainWindow::getInstance(),tr("确定要删除用户\"%1\"？").arg(strUserName))==0)
        {
            QString strErr;
                //操作数据库据删除数据
            DatabaseManager::getInstance()->deleteUser(strUserName,strErr);
                //删除model数据
            removeUserFromModel(currentRow);
        }
    }
}
